<template>
    <div class="assignment-manage">
      <!-- <y-header title="作业管理" left-arrow @click-left="onBack" /> -->
      <YHeader></YHeader>
      <div class="toolbar">
        <van-button type="primary" icon="plus" @click="showCreateAssignment = true">新建作业</van-button>
      </div>
      
      <div class="assignment-list">
        <van-empty v-if="assignments.length === 0" description="暂无作业" />
        
        <van-cell-group v-for="assignment in assignments" :key="assignment.id" inset style="margin-bottom: 12px;">
          <van-cell :title="assignment.title" is-link @click="viewAssignmentDetail(assignment)">
            <template #label>
              <div class="assignment-meta">
                <div class="deadline">
                  <van-icon name="clock-o" /> 截止日期：{{ formatDate(assignment.deadline) }}
                </div>
                <div class="status">
                  <van-tag :type="getStatusTagType(assignment.status)">{{ getStatusText(assignment.status) }}</van-tag>
                </div>
              </div>
            </template>
          </van-cell>
          
          <van-cell title="提交情况">
            <template #value>
              <div class="submission-stats">
                <span>{{ assignment.submittedCount }}/{{ assignment.totalCount }}</span>
                <van-progress :percentage="getSubmissionPercentage(assignment)" :show-pivot="false" />
              </div>
            </template>
          </van-cell>
          
          <van-cell>
            <template #title>
              <div class="action-buttons">
                <van-button size="small" @click="editAssignment(assignment)">编辑</van-button>
                <van-button size="small" type="primary" plain @click="viewSubmissions(assignment)">查看提交</van-button>
                <van-button size="small" type="danger" @click="confirmDeleteAssignment(assignment)">删除</van-button>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 创建/编辑作业弹窗 -->
      <van-dialog
        v-model:show="showCreateAssignment"
        :title="isEditing ? '编辑作业' : '新建作业'"
        show-cancel-button
        @confirm="saveAssignment"
      >
        <van-form>
          <van-field
            v-model="assignmentForm.title"
            name="title"
            label="标题"
            placeholder="请输入作业标题"
            :rules="[{ required: true, message: '请输入作业标题' }]"
          />
          <van-field
            v-model="assignmentForm.description"
            name="description"
            label="描述"
            type="textarea"
            rows="3"
            placeholder="请输入作业描述"
          />
          <van-field
            v-model="assignmentForm.deadline"
            name="deadline"
            label="截止日期"
            readonly
            placeholder="请选择截止日期"
            @click="showDatePicker = true"
          />
          <van-field name="attachment" label="附件">
            <template #input>
              <van-uploader />
            </template>
          </van-field>
        </van-form>
      </van-dialog>
      
      <!-- 日期选择器 -->
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="selectedDate"
          type="datetime"
          title="选择截止日期"
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
        />
      </van-popup>
      
      <!-- 删除确认弹窗 -->
      <van-dialog
        v-model:show="showDeleteConfirm"
        title="确认删除"
        show-cancel-button
        @confirm="deleteAssignment"
      >
        <p style="padding: 20px 16px;">确定要删除作业"{{ assignmentToDelete?.title }}"吗？该操作不可撤销。</p>
      </van-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showSuccessToast } from 'vant';
  import YHeader from '@/components/YHeader.vue';
  
  interface Assignment {
    id: string;
    title: string;
    description: string;
    deadline: string;
    status: 'draft' | 'published' | 'ended';
    submittedCount: number;
    totalCount: number;
    attachments?: string[];
  }
  
  const router = useRouter();
  const route = useRoute();
  const courseId = computed(() => route.query.courseId as string);
  
  // 模拟数据
  const assignments = ref<Assignment[]>([
    {
      id: '1',
      title: '第一次作业：Vue基础',
      description: '完成Vue3组件的基本使用',
      deadline: '2023-11-20T23:59:59',
      status: 'published',
      submittedCount: 32,
      totalCount: 42
    },
    {
      id: '2',
      title: '第二次作业：状态管理',
      description: '使用Pinia进行状态管理',
      deadline: '2023-12-05T23:59:59',
      status: 'draft',
      submittedCount: 0,
      totalCount: 42
    }
  ]);
  
  const showCreateAssignment = ref(false);
    const showDatePicker = ref(false);
    const showDeleteConfirm = ref(false);
const isEditing = ref(false);
const assignmentToDelete = ref<Assignment | null>(null);
const selectedDate = ref(new Date());

const assignmentForm = ref({
  id: '',
  title: '',
  description: '',
  deadline: '',
  status: 'draft' as 'draft' | 'published' | 'ended'
});

onMounted(async () => {
  // 实际项目中这里应该调用API获取作业列表
  // if (courseId.value) {
  //   try {
  //     const res = await getAssignmentList(courseId.value);
  //     assignments.value = res.data;
  //   } catch (error) {
  //     console.error('获取作业列表失败', error);
  //   }
  // }
});

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const getSubmissionPercentage = (assignment: Assignment) => {
  if (assignment.totalCount === 0) return 0;
  return Math.round((assignment.submittedCount / assignment.totalCount) * 100);
};

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'draft': return 'default';
    case 'published': return 'primary';
    case 'ended': return 'success';
    default: return 'default';
  }
};

const getStatusText = (status: string) => {
  switch (status) {
    case 'draft': return '草稿';
    case 'published': return '已发布';
    case 'ended': return '已结束';
    default: return '未知';
  }
};

const viewAssignmentDetail = (assignment: Assignment) => {
  router.push({
    path: `/classroom/manage/assignments/detail`,
    query: {
      courseId: courseId.value,
      assignmentId: assignment.id
    }
  });
};

const editAssignment = (assignment: Assignment) => {
  isEditing.value = true;
  assignmentForm.value = {
    id: assignment.id,
    title: assignment.title,
    description: assignment.description,
    deadline: assignment.deadline,
    status: assignment.status
  };
  selectedDate.value = new Date(assignment.deadline);
  showCreateAssignment.value = true;
};

const resetAssignmentForm = () => {
  assignmentForm.value = {
    id: '',
    title: '',
    description: '',
    deadline: '',
    status: 'draft'
  };
  isEditing.value = false;
};

const onDateConfirm = (date: Date) => {
  selectedDate.value = date;
  assignmentForm.value.deadline = date.toISOString();
  showDatePicker.value = false;
};

const saveAssignment = async () => {
  // 实际项目中这里应该调用API保存作业
  try {
    if (isEditing.value) {
      // 修改现有作业
      const index = assignments.value.findIndex(a => a.id === assignmentForm.value.id);
      if (index !== -1) {
        assignments.value[index] = {
          ...assignments.value[index],
          title: assignmentForm.value.title,
          description: assignmentForm.value.description,
          deadline: assignmentForm.value.deadline,
          status: assignmentForm.value.status
        };
      }
      showSuccessToast('作业已更新');
    } else {
      // 创建新作业
      const newId = String(Date.now());
      assignments.value.push({
        id: newId,
        title: assignmentForm.value.title,
        description: assignmentForm.value.description,
        deadline: assignmentForm.value.deadline,
        status: 'draft',
        submittedCount: 0,
        totalCount: 42 // 这里应该是学生总数
      });
      showSuccessToast('作业已创建');
    }
    
    resetAssignmentForm();
  } catch (error) {
    console.error('保存作业失败', error);
    showToast('操作失败');
  }
};

const confirmDeleteAssignment = (assignment: Assignment) => {
  assignmentToDelete.value = assignment;
  showDeleteConfirm.value = true;
};

const deleteAssignment = async () => {
  if (!assignmentToDelete.value) return;
  
  // 实际项目中这里应该调用API删除作业
  // try {
  //   await deleteAssignmentApi(assignmentToDelete.value.id);
  //   assignments.value = assignments.value.filter(a => a.id !== assignmentToDelete.value?.id);
  //   showSuccessToast('作业已删除');
  // } catch (error) {
  //   console.error('删除作业失败', error);
  //   showToast('删除失败');
  // }
  
  // 模拟删除
  assignments.value = assignments.value.filter(a => a.id !== assignmentToDelete.value?.id);
  showSuccessToast('作业已删除');
};

const viewSubmissions = (assignment: Assignment) => {
  router.push({
    path: `/classroom/manage/assignments/submissions`,
    query: {
      courseId: courseId.value,
      assignmentId: assignment.id
    }
  });
};
</script>

<style scoped>
.assignment-manage {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.toolbar {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
}

.assignment-list {
  padding: 0 8px;
}

.assignment-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.deadline {
  color: #646566;
  font-size: 13px;
  display: flex;
  align-items: center;
}

.deadline .van-icon {
  margin-right: 4px;
}

.submission-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.submission-stats span {
  font-size: 12px;
  color: #646566;
  margin-bottom: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}
</style>
  
  